package threads;

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

//Executor线程框架试例
public class ExecutorsTest1 {
    public  static void main(String [] args)throws InterruptedException
    {
        Server server=new Server();//引入线程服务器池
        for(int i=0;i<100;i++)
        {
            System.out.println("一个任务正在到达:");
            Task task=new Task("任务"+i);
            Thread.sleep(1000);
            server.submitTask(task);

        }
        server.endServer();
    }

}
class Task implements Runnable
{
    private String name;
    public Task(String name)
    {
        this.name=name;
    }
    public void run()
    {
        Long dura=(long)(Math.random()*1000);//产生随机数
       System.out.println("正在执行的线程任务是" +Thread.currentThread());
        try {
            Thread.sleep(dura);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("完成的线程名是："+Thread.currentThread().getName());
    }
}
class Server
{
    private ThreadPoolExecutor executor;//定义线程池变量
    public Server()
    {
        //构造函数
        executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();//创建变化线程池
       // executor=(ThreadPoolExecutor) Executors.newFixedThreadPool(5);//或者定义固定的线程数
    }
    public void submitTask(Task task)
    {
        //向线程池提交任务的方法
        System.out.println("一个新的任务到达");
        executor.execute(task);//向线程池提交任务
        System.out.println("线程数量为："+executor.getPoolSize());
        System.out.println("正在运行的线程数是："+executor.getActiveCount());
        System.out.println("完成的线程数为"+executor.getCompletedTaskCount());
    }
    public void endServer()
    {
        executor.shutdown();
        //关闭线程池
    }

}
